﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using log4net;
using ThousandFunClient.Util;
using ThousandFunClient.model;
using System.Timers;
using System.Collections;
using System.Reflection;

//注意下面的语句一定要加上，指定log4net使用.config文件来读取配置信息  08.//如果是WinForm（假定程序为MyDemo.exe，则需要一个MyDemo.exe.config文件）  09.//如果是WebForm，则从web.config中读取相关信息  
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ThousandFunClient
{
    public partial class ThousandFun : Form
    {
        public ThousandFun()
        {
            InitializeComponent();
        }

        private void btn_sendMsg_Click(object sender, EventArgs e)
        {

    
            SP_Main.Write(textBox1.Text);
            logger.Error(textBox1.Text);
            loggersp.Error("Send:"+textBox1.Text);

            //配置的测试
            //SoftwareSettings softSettings = ConfigurationManager.GetSection("SoftwareSettings") as SoftwareSettings;  
 
            //foreach (string key in softSettings.LoadSettings.Settings.Keys)  
            //{  
                
            //   MessageBox.Show(key+"|||"+softSettings.LoadSettings[key]); 
 
            //}
            //softSettings.PathSetting.SearchSubPath = false;
            //MessageBox.Show(softSettings.PathSetting.SavePath);
            //MessageBox.Show(softSettings.PathSetting.SearchSubPath.ToString());


            //System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //IDictionary dic = ConfigurationManager.GetSection("MySectionGroup/MySecondSection") as IDictionary;
            //string resultValue = dic["Second"].ToString();
            //MessageBox.Show(resultValue);


            //logger.Error("sadfas");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            Hashtable ht = TFConfig.GetInstance().HtTimer;

            foreach (DictionaryEntry de in ht) //ht为一个Hashtable实例
            {

                System.Timers.Timer bTimer = (System.Timers.Timer)de.Value;
                bTimer.Interval = Double.Parse((String)de.Key);
                bTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
                bTimer.Enabled = true;

            }

            //System.Timers.Timer bTimer = new System.Timers.Timer();
            //bTimer.Interval = 3* 1000;
            //bTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
            //bTimer.Enabled = true;

            //System.Timers.Timer aTimer = new System.Timers.Timer();
            //aTimer.Interval = 2 * 1000;
            //aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
            //aTimer.Enabled = true;

            //label2.Text += bTimer.GetHashCode()+"fisher"+aTimer.GetHashCode();
            //ConfigUtil.initConfig();

            //PortUtil.SetPortByConfig(SP_Main, TFConfig.GetInstance().PortConfigA);

            //label1.Text = " " + "portName:" + SP_Main.PortName + "   baudRate:" + SP_Main.BaudRate;

            //PortUtil.OpenCOM(SP_Main);

            
            
            //LinqXML l = new LinqXML();
            //l.SetBind();
            //类的测试
            //string strSendcc;
            //strSendcc = "ddd";
            //TFModel tfsend = new TFModel(strSendcc, "");
            //MessageBox.Show(tfsend.StrSend);
            //for (int i = 1; i<10000;i++ )
            //{
            //    loggersp.Error("sadfas阿asdfasdfewqrtweqtasdfsdagsda");
            //}

        }

        private void TimeEvent(object source, ElapsedEventArgs e)
        {

            Hashtable hb = TFConfig.GetInstance().HtBatchCMD;

            String nowInterval = ((System.Timers.Timer)source).Interval.ToString();
            foreach (DictionaryEntry de in hb) 
            {
                SendCMDConfig sendCMDConfig = (SendCMDConfig)de.Value;
                if (sendCMDConfig.Interval.Equals(nowInterval))
                {
                    SP_Main.Write(sendCMDConfig.SendCMD);
                }

            }
       

            // 得到 hour minute second  如果等于某个值就开始执行某个程序。
            int intHour  = e.SignalTime.Hour;
            int intMinute = e.SignalTime.Minute;
            int intSecond = e.SignalTime.Second;
          //label1.Text = intHour.ToString() + ":" + intMinute.ToString() + ":" + intSecond.ToString();
  //// 定制时间； 比如 在10：30 ：00 的时候执行某个函数
  //int iHour  = 10;
  //int iMinute = 30;
  //int iSecond = 00;
  //// 设置　 每秒钟的开始执行一次
  //    if( intSecond == iSecond )
  //    {
  //        MessageBox.Show(iHour.ToString() + ":" + iMinute.ToString() + ":" + iSecond.ToString());
  //        //label2.Text = iHour.ToString()+":"+iMinute.ToString()+":"+iSecond.ToString();
  //    }
  //// 设置　每个小时的３０分钟开始执行
  //    if( intMinute == iMinute && intSecond == iSecond )
  //    {
  //      Console.WriteLine("每个小时的３０分钟开始执行一次！");
  //    }

  //  // 设置　每天的１０：３０：００开始执行程序
  //        if( intHour == iHour && intMinute == iMinute  && intSecond == iSecond )
  //        {
  //          Console.WriteLine("在每天１０点３０分开始执行！");
  //        }
        }


        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static readonly ILog loggersp = LogManager.GetLogger("ThousandFun.client.translog");

        private void SP_Main_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int int_Len = SP_Main.BytesToRead;
            byte[] buf = new byte[int_Len];
            SP_Main.Read(buf, 0, int_Len);
            string get = ASCIIEncoding.ASCII.GetString(buf);

            Hashtable hl = TFConfig.GetInstance().HtLogger;

            //if (sendCMDConfig.Interval.Equals(nowInterval))
            //{
            //    ILog logger = hl[sendCMDConfig.LoggerName];
            //}

            //logger.Error(get);
            loggersp.Error("reply:" + get);

        }

        private void btn_readConfig_Click(object sender, EventArgs e)
        {
            ConfigUtil.initConfig();

            PortUtil.SetPortByConfig(SP_Main, TFConfig.GetInstance().PortConfigA);

            label1.Text = " " + "portName:" + SP_Main.PortName + "   baudRate:" + SP_Main.BaudRate;

            PortUtil.OpenCOM(SP_Main);
            
            // ILog loggerspcc = LogManager.GetLogger("ThousandFun.client.translog");
            // ILog loggerspff= LogManager.GetLogger("ThousandFun.client.translog");
            // if (loggerspcc.Equals(loggerspff))
            // {
            //     MessageBox.Show("equalstrue");
            // }
            //else
            // {
            //     MessageBox.Show("equalsfalse");
            // }
            // if (loggerspcc==loggerspff)
            // {
            //     MessageBox.Show("==true");
            // }
            // else
            // {
            //     MessageBox.Show("==false");
            // }

             ILog loggerspfe = LogManager.GetLogger("ThousandFun.client.translog");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            String use = "";
            String nouse = "";
            for (int i = 1; i < 50; i++)
            {


                try
                {
                    SP_Main.PortName = "com" + i.ToString();
                    SP_Main.Open();
                    SP_Main.Close();
                }
                catch (Exception ec)
                {
                    nouse = nouse + "com" + i.ToString();
                    continue;
                }
                use = use + "com" + i.ToString();
            }

            MessageBox.Show("cc");
        }

        private void btn_config_Click(object sender, EventArgs e)
        {
            //OpenWindow(typeof(Fm_Config).ToString());
            
            
            
            DialogResult dr = fm_Config.ShowDialog();
            
           
        }

        
        private Fm_Config fm_Config = new Fm_Config();
       
    }
}
